package servlet;

import entity.Order;
import util.CSVUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by dylan-pc on 2017/8/26.
 */
@WebServlet(name = "exportOrderServlet", urlPatterns = {"/exportOrder"})
public class exportOrderServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置response
        response.setContentType("application/x-download;charset=utf-8");
        //生成样例数据

        List<Order> orders = Arrays.asList(new Order("sa20170826001", "shipping", "2017/8/26", "罗西尼女表", 499),
                new Order("sa20170826002", "submit", "2017/8/26", "耐克篮球鞋", 1099),
                new Order("sa20170826001", "finish", "2017/8/26", "新百伦G500慢跑鞋", 234));

        //设置文件名
        SimpleDateFormat dtf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String curDateStr = dtf.format(new Date());
        String fileName = "订单列表-" + curDateStr + ".csv";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

        //获得打印流
        PrintWriter pw = response.getWriter();
        pw.println("订单号, 订单状态, 下单日期,商品名称,商品价格");

        StringBuilder sb = new StringBuilder();
        for (Order o : orders) {
            sb.append(o.getOrderNo() + "," + o.getOrderStatus() + "," + o.getOrderDt() + "," + o.getProductName() + "," + Double.toString(o.getPrice()) + "\n");
        }

        pw.print(sb);
        pw.close();

    }
}
